$(document).ready(function(){
					var VAL = {
						NORMAL : "0000000",
						EVT_USER : $("#userId").text(),
						T_XPTOOLOPE : "XPTOOLOPE",
						T_XPLSTEQP : "XPLSTEQP",
						T_XPTOOLCHK : "XPTOOLCHK",
					    T_XPBISOPE  :"XPBISOPE"
					};
					var controlsQuery = {
						W : $(window),
						opeSelect : $("#opeSelect"),
						toolSelect : $("#toolSelect"),
						remarkTxta : $("#remarkTxta"),
						toolStatusSelect : $("#toolStatusSelect"),
						beginTimeDatepicker : $("#beginTimeDatepicker"),
						endTimeDatepicker : $("#endTimeDatepicker"),
						pmtype : $("#pmCateSel"),

						mainGrdP : {
							grdId : $("#toolPmListGrd"),
							grdPgText : "#toolPmListPg",
							fatherDiv : $("#toolPmListDiv")
						},
					    mainGrdS : {
						    grdId : $("#toolSmListGrd"),
						    grdPgText : "#toolSmListPg",
						   fatherDiv : $("#toolSmListDiv")
					}
					};

					/**
					 * All button's jquery object
					 * 
					 * @type {Object}
					 */
					var btnQuery = {
						f1 : $("#f1_btn"),
						f8 : $("#f8_btn")
					};

					/**
					 * All tool functions
					 * 
					 * @type {Object}
					 */
					var toolFunc = {
						clearInput : function() {
							controlsQuery.remarkTxta.val("");
						},

						/**
						 * Set data for select
						 * 
						 * @param dataCnt
						 * @param arr
						 * @param selVal
						 * @param queryObj
						 */
						setSelectDate : function(dataCnt, arr, selVal, queryObj) {
							var i, realCnt;

							queryObj.empty();
							realCnt = parseInt(dataCnt, 10);

							if (realCnt == 1) {
								if (arr.hasOwnProperty(selVal)) {
									queryObj.append("<option value="
											+ arr[selVal] + ">" + arr[selVal]
											+ "</option>")
								}
							} else if (realCnt > 1) {
								for (i = 0; i < realCnt; i++) {
									if (arr[i].hasOwnProperty(selVal)) {
										queryObj.append("<option value="
												+ arr[i][selVal] + ">"
												+ arr[i][selVal] + "</option>");
									}
								}
							}
							 queryObj.select2({
					    	    	theme : "bootstrap"
					    	    });
						},
						inipmtype : function(){
							var inTrxObjpmcate,outTrxObjpmcate;
							inTrxObjpmcate = {
									trx_id : 'XPLSTDAT',
									action_flg : 'Q',
									iary : {
										data_cate : "PMTP",
									}
								};
								outTrxObjpmcate = comTrxSubSendPostJson(inTrxObjpmcate);
								if (outTrxObjpmcate.rtn_code == VAL.NORMAL) {
									_setSelectDate(outTrxObjpmcate.tbl_cnt, outTrxObjpmcate.oary,
											"data_id", "data_ext", controlsQuery.pmtype,
											false);
								}
						},
				        iniOpeSelect : function(){
				        	var inObj, 
				        		outObj;
				        		ope_ary = [];
				        	var inObj, 
				        		outObj,
				        		ope_ary = [];
				            var user_id = VAL.EVT_USER;
				            var iaryB = {
				                user_id     : user_id
				            };
				            inObj = {
				                trx_id      : VAL.T_XPBISOPE,
				                action_flg  : 'I',
				                iaryB       : iaryB
				            };
				            outObj = comTrxSubSendPostJson(inObj);
				            if (outObj.rtn_code == VAL.NORMAL) {
				                toolFunc.setOpeSelectDate(outObj.tbl_cnt, outObj.oary,
				                    "ope_id", "ope_ver", "proc_id", "ope_dsc", controlsQuery.opeSelect);
				            }
				        },
				        setOpeSelectDate : function(dataCnt, arr, selVal, selVal2, selVal3, selTxt, queryObj, firstSpace){
				            var i, realCnt;

				            queryObj.empty();
				            if(firstSpace === true){
				                queryObj.append("<option ></option>");
				            }

				            realCnt = parseInt( dataCnt, 10);

				            if( realCnt == 1 ){
				                    queryObj.append("<option value="+ arr[selVal] + "@" + arr[selVal2] + "@" + arr[selVal3] + "@" + arr[selTxt] +">"+ arr[selTxt] +"</option>");
				            }else if( realCnt > 1 ){
				                for( i = 0; i < realCnt; i++ ){
				                        queryObj.append("<option value="+ arr[i][selVal] + "@" + arr[i][selVal2] + "@" + arr[i][selVal3] +"@" + arr[i][selTxt] +">"+ arr[i][selTxt] +"</option>");
				                }
				            }
				            queryObj.select2({
				    	    	theme : "bootstrap"
				    	    });
				        },
				        iniToolSelect : function(){
				            var inObj, outObj, ope_id, ope_ver,
				                ope_info, ope_info_ary;

				            ope_info = $.trim(controlsQuery.opeSelect.val());

				            if(!ope_info){
				                return false;
				            }

				            ope_info_ary = ope_info.split("@");
				            ope_id = ope_info_ary[0];
				            ope_ver = ope_info_ary[1];

				            if(!ope_id){
				                console.error(ope_id);
				                return false;
				            }

				            if(!ope_ver){
				                console.error(ope_ver);
				                return false;
				            }
				            inObj = {
				                    trx_id      : VAL.T_XPLSTEQP,
				                    action_flg  : 'F'           ,
				                    ope_id      : ope_id        ,
				                    ope_ver     : ope_ver       ,
				                    user_id     : VAL.EVT_USER 
				                };
				            outObj = comTrxSubSendPostJson(inObj);
				            if (outObj.rtn_code == VAL.NORMAL) {
				                _setSelectDate(outObj.tbl_cnt, outObj.oary, "tool_id", "tool_id", "#toolSelect", false);
				            }
				        },
						iniDateTimePicker : function() {
							var beginTimeDate, endTimeDate;
							controlsQuery.beginTimeDatepicker.datetimepicker({
								language : 'zh-CN'
							});
							controlsQuery.endTimeDatepicker.datetimepicker({
								language : 'zh-CN'
							});

							beginTimeDate = controlsQuery.beginTimeDatepicker
									.data("datetimepicker");
							beginTimeDate.setLocalDate(new Date());

							endTimeDate = controlsQuery.endTimeDatepicker
									.data("datetimepicker");
							endTimeDate.setLocalDate(new Date());
						},
						showDataSetDialog : function(ids) {
							var rowData, itemName, grd;
							grd = controlsQuery.mainGrdP.grdId;
							rowData = grd.jqGrid("getRowData", ids);
							itemName = rowData['mes_id_fk'];
							grd._showSimpleInputDialog({
								itemName : itemName,
								callbackFn : function(data) {
									if ($.trim(data.keyInResult)) {
										rowData['pm_seq_id'] = $.trim(data.keyInResult);
										grd.jqGrid('setRowData', ids, rowData);
									}
								}
							});
						}
					};

					/**
					 * All button click function
					 * 
					 * @type {Object}
					 */
					var btnFunc = {
						// Query
						f1_func : function() {
							var inObj, outObj, tool_id,pm_type;
							tool_id = controlsQuery.toolSelect.val();
                            
							if (!tool_id) {
								showErrorDialog("", "请选择设备代码！");
								return false;
							}
                            pm_type= controlsQuery.pmtype.val();
							inObj = {
								trx_id : 'XPMLITEM',
								action_flg : 'H',
								iaryA : {
									tool_id_fk : tool_id,
									pm_type    : pm_type
								}
							};
							outObj = comTrxSubSendPostJson(inObj);
							if (outObj.rtn_code == VAL.NORMAL) {
								setGridInfo(outObj.oaryC, "#toolSmListGrd");

								var tbl_cnt = outObj.tbl_cnt_b;
								$("#dataItemEditDiv").empty();
								var str = '<table id="dataItemTbl" class="table table-striped table-bordered table-condensed" ><tr>'
									+ '<td class="Header_Text " >参数序号 </td>'
									+ '<td class="Header_Text " >参数名称 </td>'
									+ '<td class="Header_Text " >参数说明 </td>'
									+ '<td class="Header_Text " >值 </td>'
								for (var i = 0; i < tbl_cnt; i++) {
									str = str + "<tr>"
									    + '<td class=" dataItemTdCss">'
										+ outObj.oaryB[i].data_id + "</td>"
										+ '<td id ="tbl_data_group' + i
										+ '\" class=" dataItemTdCss">'
										+ outObj.oaryB[i].data_group + "</td>"
										+ '<td class=" dataItemTdCss">'
										+ outObj.oaryB[i].data_dsc + "</td>"
										+ '<td class=" dataItemTdCss">'
										+ '<input type="text" name='+ i +' class ="span2 numberCssA" id="dataItem_'
										+ i + '_Txt\" />' + "</td>"
									    + "</tr>";
								}
								str = str + "</table>";
								$(str).appendTo("#dataItemEditDiv");
								for (var i = 0; i < tbl_cnt; i++) {
								$("#dataItem_" + i + "_Txt").keypress(function(event){
										if (event.keyCode == 13) {
											dataItemKeyPressFnc(this);
										}
									});
								}
								showSuccessDialog("刷新列表成功!",1);
							}
						},
						// Update
						f8_func : function() {
			                var tool_id,begin_time,end_time,note,inTrx,outTrx,pm_type;
			                var iaryAry=[];
							tool_id = controlsQuery.toolSelect.val();
							pm_type= controlsQuery.pmtype.val();
							if (!tool_id) {
								showErrorDialog("", "请选择设备代码！");
								return false;
							}
							note = controlsQuery.remarkTxta.val();
			        	    begin_time =  $("#beginTimeDatepicker").data("datetimepicker").getLocalDate().format('yyyy-MM-dd hh:mm:ss');
			        	    end_time = $("#endTimeDatepicker").data("datetimepicker").getLocalDate().format('yyyy-MM-dd hh:mm:ss');

			                if(!note){
			                	 showErrorDialog("","请输入备注。");
				                 return false;
			                }
			                if(!begin_time){
			                	 showErrorDialog("","请输入开始时间。");
				                 return false;
			                }
			                if(!end_time){
			                	 showErrorDialog("","请输入结束时间。");
				                 return false;
			                }
			        		var tableItemCnt = 0;
			        		tableItemCnt = $("#dataItemTbl tr").length - 1;
			        		for (var i = 0; i < tableItemCnt; i++) {
			        				var iary = {
			        					data_group : $("#tbl_data_group" + i).text(),
			        					data_value : $("#dataItem_" + i + "_Txt").val(),
			        				};
			        				iaryAry.push(iary);
			        		}
			        		
			        		// Send Tx
			                inTrx={
			    		       trx_id : 'XPMLITEM',
			    		       action_flg : 'F',
			    		       data_cnt  : iaryAry.length,
			    		   	   tool_id_fk : tool_id,
			    		   	   pm_type    : pm_type,
			    		   	   ac_pm_beg_timestamp : begin_time,
			    		   	   ac_pm_end_timestamp : end_time,
			    		   	   ac_pm_note : note,
			    		   	   evt_user : VAL.EVT_USER,
			    		       iaryB : iaryAry
			                 }
			                outTrx = comTrxSubSendPostJson(inTrx);
			    		    if (outTrx.rtn_code == VAL.NORMAL) {
			    		    	showSuccessDialog("数据上报成功");
			        			$("[id^='dataItem_']").val(""); 
			    		    }
						 }
					    };

					/**
					 * Bind button click action
					 */
					var iniButtonAction = function() {
						btnQuery.f1.click(function() {
							btnFunc.f1_func();
						});
						btnQuery.f8.click(function() {
							btnFunc.f8_func();
						});
					};
					function dataItemKeyPressFnc(obj){
						var nextSelecter,uslSelector,lslSelector,usl,lsl,index,value;
						index = obj.id.split("_")[1];
						uslSelector = "#usl_"+index ;
						usl = parseFloat($(uslSelector).text());
						lslSelector = "#lsl_"+index;
						lsl = parseFloat($(lslSelector).text());
						value = parseFloat($(obj).val()); 
						if(value>usl){
							showMessengerErrorDialog("输入数值高于标准上限"+usl,2);
							$(obj).focus();
							return false;
						}else if(value<lsl){
							showMessengerErrorDialog("输入数值低于标准下限"+lsl,2);
							$(obj).focus();
							return false;
						}
						nextSelecter = "#dataItem_" +( parseInt(obj.name,10)+1 ) + "_Txt";
						$(nextSelecter).focus();	
					}
					/**
					 * grid initialization
					 */
					var iniGridInfo = function() {

						var toolSmInfoCM = [ {
							name : 'pm_date',
							index : 'pm_date',
							label : "保养日期",
							width : 120
						}, {
							name : 'pm_type',
							index : 'pm_type',
							label : "保养类型",
							width : 120,
							hidden: true
						} ,{
							name : 'pm_type_dsc',
							index : 'pm_type_dsc',
							label : "保养类型",
							width : 120
						} ];
						$("#toolSmListGrd").jqGrid({
							url : "",
							datatype : "local",
							mtype : "POST",
							height : $("#toolSmListDiv").height(),
							height : 350,
							width : $("#toolSmListDiv").width(),
							autowidth : false,// 宽度根据父元素自适应:true
							shrinkToFit : false,
							scroll : false,
							resizable : true,
							loadonce : true,
							fixed : true,
							viewrecords : true, // 显示总记录数
							pager : '#toolSmListPg',
							rownumbers : true,// 显示行号
							rowNum : 23, // 每页多少行，用于分页
							rownumWidth : 40, // 行号列宽度
							emptyrecords : true,
							pginput : true,// 可以输入跳转页数
							rowList : [ 10, 15, 20 ], // 每页多少行
							toolbar : [ true, "top" ],// 显示工具列 :
							colModel : toolSmInfoCM,
							gridComplete : function() {

							}
						})
					};

					/**
					 * Other action bind
					 */
					var otherActionBind = function() {
						// Stop from auto commit
						$("form").submit(function() {
							return false;
						});

				        controlsQuery.opeSelect.change(function(){
				        	
				            toolFunc.iniToolSelect();
				        });
					};

					/**
					 * Ini contorl's data
					 */
					var iniContorlData = function() {
						toolFunc.clearInput();

						// Tool info
						toolFunc.iniOpeSelect();
						toolFunc.iniToolSelect();

						// Time
						toolFunc.iniDateTimePicker();
						toolFunc.inipmtype();
					};

					/**
					 * Ini view, data and action bind
					 */
					var initializationFunc = function() {
						iniGridInfo();
						iniButtonAction();
						otherActionBind();
						iniContorlData();
					};

					initializationFunc();
				});
